package com.test.tool.demo.websocket;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;

/**
 * 消息发送
 *
 * @author 小八
 * @date 2022年04月25日15:49
 */
@Slf4j
@Service
//@Transactional(rollbackFor = Exception.class)
public class WebSocketServiceImpl{

    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;


    public ResponseWrapper<?> sendStompMsg(WebSocketMsgVO webSocketMsgVo) {
        String topicChannel = webSocketMsgVo.getTopicChannel();
        if (StrUtil.isNotBlank(topicChannel)) {
            topicChannel = "/" + topicChannel;
        }
        String message = JSONUtil.toJsonStr(webSocketMsgVo);
        String to = webSocketMsgVo.getTo();
        try {
            if (StrUtil.isNotBlank(to)) {
                //MD 不明原因用convertAndSendToUser不能收到，确认订阅没有问题
                simpMessagingTemplate.convertAndSendToUser(to, topicChannel, message);
//                simpMessagingTemplate.convertAndSend(topicChannel + "/" + to, message);
            } else {
                simpMessagingTemplate.convertAndSend(topicChannel, message);
            }
            return ResponseWrapper.ok();
        } catch (Exception e) {
            return ResponseWrapper.error(1000,"发送失败");
        }

    }
}
